<template>
  <div class="container mx-auto px-4 py-8" @scroll="handleScroll" ref="galleryRef">
    <div class="grid grid-cols-1 md:grid-cols-3 gap-8 py-4">
      <div v-for="item in galleryData" :key="item.id" class="flex flex-col items-center">
        <el-image :src="item.url" :preview-src-list="[item.url]" fit="cover" lazy class="w-full h-full min-h-[200px] object-cover cursor-pointer rounded-[20px] border-[1px] border-[var(--border-color)] transition-transform duration-300 hover:scale-105"
            preview-teleported :preview-options="{
              zIndex: 9999,
          }" />
          <!-- 图片url -->
          <a :href="item.url" target="_blank" class="text-center text-[var(--text-color)] text-sm mt-2 hover:text-[var(--pink-color)]">{{ item.url || '无url' }}</a>
      </div>
    </div>
    <!-- 触底加载提示 -->
    <div v-if="loading" class="text-center text-[var(--text-color)]">加载中...</div>
    <div v-else-if="!hasMore" class="text-center text-[var(--text-color)]">没有更多图片了</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getFiles } from '@/apis/upload'
import { ElMessage } from 'element-plus'
import { throttle } from 'lodash-es'

const galleryRef = ref(null);
const galleryData = ref([]);
const loading = ref(false);
const hasMore = ref(true);
const currentPage = ref(1);
const itemsPerPage = 6;

// 获取图片数据
const fetchData = async () => {
  if (loading.value || !hasMore.value) return;
  
  loading.value = true;
  try {
    const res = await getFiles({
      page: currentPage.value,
      limit: itemsPerPage
    });

    if (res.success && res.data?.files) {
      // 如果是第一页，则替换数据，否则追加数据
      if (currentPage.value === 1) {
        galleryData.value = res.data.files;
      } else {
        galleryData.value.push(...res.data.files);
      }

      // 判断是否还有更多数据
      hasMore.value = galleryData.value.length < (res.data.pagination?.totalItems || 0);
      currentPage.value++;
    }
  } catch (error) {
    ElMessage.error('获取图片列表失败');
    console.error('Failed to fetch images:', error);
  } finally {
    loading.value = false;
  }
};

// 处理滚动事件，实现触底加载（使用节流优化性能）
const handleScroll = throttle(() => {
  if (!galleryRef.value || loading.value || !hasMore.value) return;
  
  const { scrollTop, scrollHeight, clientHeight } = galleryRef.value;
  // 当滚动到距离底部100px时触发加载
  if (scrollHeight - scrollTop - clientHeight < 100) {
    fetchData();
  }
}, 300); // 300ms 节流间隔

// 初始化加载第一页数据
onMounted(() => {
  fetchData();
});
</script>